<template>
  <div class="wave-chart">
    <ECharts :options="chartOptions" :height="height" :width="width" />
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import ECharts from "@/components/ECharts/index.vue";
import type { WaveDataItem } from "@/api/hmi/chart.api";
import type { EChartsCoreOption } from "echarts/core";

interface Props {
  /** 波形数据列表 */
  data: WaveDataItem[];
  /** 图表宽度 */
  width?: string;
  /** 图表高度 */
  height?: string;
  /** 图表标题 */
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  width: "100%",
  height: "400px",
  title: "波形图",
});

// 计算图表配置
const chartOptions = computed<EChartsCoreOption>(() => {
  const { data } = props;

  if (!data || data.length === 0) {
    return {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
      },
    };
  }

  // 准备系列数据
  const series = data.map((item, index) => {
    const colors = [
      "#409EFF",
      "#67C23A",
      "#E6A23C",
      "#F56C6C",
      "#909399",
      "#C71585",
      "#FF6347",
      "#32CD32",
    ];

    return {
      name: item.Name,
      type: "line",
      data: item.Data,
      smooth: true,
      lineStyle: {
        color: colors[index % colors.length],
        width: 2,
      },
      itemStyle: {
        color: colors[index % colors.length],
      },
      emphasis: {
        lineStyle: {
          width: 3,
        },
      },
    };
  });

  const legendData = data.map((item) => item.Name);

  // 生成X轴数据（采样点索引）
  const maxDataLength = Math.max(...data.map((item) => item.DataNums));
  const xAxisData = Array.from({ length: maxDataLength }, (_, i) => i);

  return {
    title: {
      text: props.title,
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
      formatter: (params: any) => {
        let result = `采样点: ${params[0].axisValue}<br/>`;
        params.forEach((param: any) => {
          result += `${param.seriesName}: ${param.value}<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: legendData,
      top: 30,
      type: "scroll",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "5%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      name: "采样点",
      nameLocation: "middle",
      nameGap: 40,
      axisLabel: {
        interval: "auto",
      },
    },
    yAxis: {
      type: "value",
      name: "幅值",
      nameLocation: "middle",
      nameGap: 50,
      scale: true,
    },
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100,
      },
      {
        start: 0,
        end: 100,
        height: 20,
        bottom: 30,
      },
    ],
    series,
  };
});
</script>

<style scoped>
.wave-chart {
  width: 100%;
  height: 100%;
}
</style>
